/**
 * 
 */
package com.aspire.android.heliar.activities;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.aspire.android.heliar.Heliar;
import com.aspire.android.heliar.R;
import com.aspire.android.heliar.pub.Pub;
import com.aspire.android.heliar.pub.PubManager;
import com.aspire.android.heliar.ui.ImageListViewAdapter;
import com.aspire.android.heliar.utils.ContextFactory;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author panglei
 * 
 */
public class PubListActivity extends Activity {

	public static final String PUB_LIST_TITLE = "pubTitle";
	public static final String PUB_LIST_DESC = "pubDesc";
	public static final String PUB_LIST_COVER = "pubCover";

	public static final int PUB_IMAGE_WIDTH = 40;
	public static final int PUB_IMAGE_HEIGHT = 40;

	public static final int MENU_SYNC_RAW_DATA = 1;

	public static final int ITEM_MENU_VIEW = 100;
	public static final int ITEM_MENU_DELETE = 101;
	public static final int ITEM_MENU_LOCK = 102;
	public static final int ITEM_MENU_UNLOCK = 103;
	public static final int ITEM_MENU_SHARE = 104;

	public static final String KEY_MESSAGE_STEP = "MESSAGE_STEP";
	public static final int STEP_SYNC_RAW_DATA = 0;

	public static final String INTENT_EXTRA_PUB_POSITION = "position";

	private ProgressDialog syncRawDataDialog;

	private ImageListViewAdapter adapter;
	private ListView listView;

	Handler progressHandler = new Handler() {
		public void handleMessage(Message message) {
			Bundle b = message.getData();
			switch (b.getInt(KEY_MESSAGE_STEP)) {
			case STEP_SYNC_RAW_DATA:
				Log.d(Heliar.LOG_TAG, "Sync Data refresh list");
				refreshListData();
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		init();
		refreshListData();
	}

	public static List<Map<String, Object>> getPubList() {
		List<Map<String, Object>> pubList = new LinkedList<Map<String, Object>>();

		List<Pub> pubs = PubManager.getInstance().getPubList();
		for (Pub pub : pubs) {
			Map<String, Object> item = new HashMap<String, Object>();
			item.put(PUB_LIST_TITLE, pub.getTitle());
			item.put(PUB_LIST_DESC, pub.getDesc());

			if (pub.getCoverFilepath() == null) {
				if (pub.getCover() == null) {
					item.put(PUB_LIST_COVER, R.drawable.default_pub_icon);
				} else {
					item.put(PUB_LIST_COVER, resize(pub.getCover().getBitmap()));
				}
			} else {
				File coverFile = new File(pub.getCoverFilepath());
				if (coverFile.exists()) {
					item.put(
							PUB_LIST_COVER,
							new BitmapDrawable(BitmapFactory.decodeFile(pub
									.getCoverFilepath())));
				} else {
					item.put(PUB_LIST_COVER, R.drawable.default_pub_icon);
				}
			}

			pubList.add(item);
		}

		return pubList;
	}

	public static BitmapDrawable resize(Bitmap bitmap) {

		return new BitmapDrawable(Bitmap.createScaledBitmap(bitmap,
				PUB_IMAGE_WIDTH, PUB_IMAGE_HEIGHT, false));
	}

	final public void refreshListData() {
		listView = new ListView(ContextFactory.getInstance());
		listView.setFastScrollEnabled(true);

		adapter = new ImageListViewAdapter(ContextFactory.getInstance(),
				getPubList(), R.layout.pub_list_row, new String[] {
						PUB_LIST_TITLE, PUB_LIST_DESC, PUB_LIST_COVER },
				new int[] { R.id.pubTitle, R.id.pubDesc, R.id.pubCover });
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View v,
					int position, long id) {
				Intent intent = new Intent(ContextFactory.getInstance(),
						PubOneFrameActivity.class);
				intent.putExtra(INTENT_EXTRA_PUB_POSITION, position);
				startActivityForResult(intent, 0);

			}
		});

		/*
		listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

			@Override
			public void onCreateContextMenu(ContextMenu menu, View view,
					ContextMenuInfo info) {

				// How to get long click list item
				AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) info;
				TextView textView = (TextView) menuInfo.targetView
						.findViewById(R.id.pubTitle);

				menu.setHeaderTitle(textView.getText());
				menu.add(0, ITEM_MENU_VIEW, 0,
						R.string.pub_list_activity_item_menu_view_title);
				menu.add(0, ITEM_MENU_DELETE, 0,
						R.string.pub_list_activity_item_menu_delete_title);
				menu.add(0, ITEM_MENU_LOCK, 0,
						R.string.pub_list_activity_item_menu_lock_title);
				menu.add(0, ITEM_MENU_SHARE, 0,
						R.string.pub_list_activity_item_menu_share_title);

			}
		});
		*/

		listView.setAdapter(adapter);
		setContentView(listView);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();

		int itemPosition = menuInfo.position;

		switch (item.getItemId()) {
		case ITEM_MENU_VIEW:
			Intent intent = new Intent(ContextFactory.getInstance(),
					PubOneFrameActivity.class);
			intent.putExtra(INTENT_EXTRA_PUB_POSITION, itemPosition);
			startActivityForResult(intent, 0);
			break;
		}

		return super.onContextItemSelected(item);
	}

	public void init() {
		ContextFactory.init(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		ContextFactory.init(this);
		refreshListData();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		int order = 0;
		menu.add(0, MENU_SYNC_RAW_DATA, order,
				R.string.pub_list_activity_menu_sync_raw_data);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_SYNC_RAW_DATA:
			syncRawData();
			break;
		}
		return false;
	}

	public void syncRawData() {
		syncRawDataDialog = new ProgressDialog(this);
		syncRawDataDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		syncRawDataDialog
				.setTitle(R.string.pub_list_activity_progress_bar_sync_raw_data_title);
		syncRawDataDialog
				.setMessage(this
						.getString(R.string.pub_list_activity_progress_bar_sync_raw_data_tips));
		syncRawDataDialog.setIndeterminate(false);
		syncRawDataDialog.setCancelable(true);
		syncRawDataDialog.show();

		// Call SyncRawData thread
		new Thread() {
			public void run() {
				PubManager.getInstance().loadLocalStorePubs();
				PubManager.getInstance().syncRawDataToPub();

				Message message = progressHandler.obtainMessage();
				Bundle b = new Bundle();
				b.putInt(KEY_MESSAGE_STEP, STEP_SYNC_RAW_DATA);
				message.setData(b);
				progressHandler.sendMessage(message);

				syncRawDataDialog.cancel();

			}
		}.start();
	}

}
